﻿using Gecko.Entities;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate.Linq;

namespace Gecko.Respositories
{
    public class RepositoryBase<T> : IRepository<T> where T : class, IEntity
    {
        public ISession Session
        {
            get;
            set;
        }
        public RepositoryBase(ISession session)
        {
            Session = session;
        }

        public IList<T> GetAll()
        {
            return Session.Query<T>().ToList();
        }

        public T Get(int id)
        {
            return Session.Get<T>(id);
        }

        public IList<T> Get(int start, int limit)
        {
            return Session.Query<T>().Skip(start).Take(limit).ToList();
        }

        public IList<T> Get(System.Linq.Expressions.Expression<Func<T, bool>> predicate, System.Linq.Expressions.Expression<Func<T, T>> order, bool desc = false, int start = 0, int limit = 100)
        {
            IQueryable<T> query = Session.Query<T>();
            if (predicate != null)
            {
                query = query.Where<T>(predicate);
            }
            if (order != null)
            {
                if (desc)
                {
                    query = query.OrderByDescending(order);
                }
                query = query.OrderBy(order);
            }
            return query.Skip<T>(start).Take<T>(limit).ToList();
        }

        public void Add(T entity)
        {
            Session.Persist(entity);
        }

        public void Update(T entity)
        {
            Session.Merge<T>(entity);
        }

        public void Delete(T entity)
        {
            Session.Delete(entity);
        }


        public int Count(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            return Session.Query<T>().Where(predicate).Count();
        }
    }
}